var lang;
var Genre;
var URI_SHORT_GENRE = "u";
var CUSTOM_SHORT_GENRE = "c";
var TEMP_SHORT_GENRE = "t";
var idStr ;

var openOp ;
$(document).ready(function() {
	Genre = $("#genre").val();
	openOp = $("#openOp").val();
	idStr = $("#idStr").val();
//	$(".toCollection").linkbutton();
	if(openOp=="relation"){
		onClickTabBar($("#tab-relation"));
	}else{
		onClickTabBar($("#tab-entity"));
	}
					lang = $("#display-lang").val();
					var ok_btn;
					var cancel_btn;
					var continue_btn;
					if(lang == 'en'){
						ok_btn = "OK";
						cancel_btn = "Cancel";
						continue_btn = "Continue";
					}else if(lang == 'zh'){
						ok_btn = "确定";
						cancel_btn = "取消";
						continue_btn = "继续";
					}
					checkContentLengthInDs($(".comment-box"));
					var dtitle;
					if(lang == 'en'){
						dtitle = "Bookmark";
					}else if(lang == 'zh'){
						dtitle = "收藏";
					}
					$("#bookmark_op").dialog({
						bgiframe : true,
						autoOpen : false,
						width : 400,
						title : dtitle,
						modal : true,
						buttons : [{
							text: ok_btn,
							click : function() {
								if (nameCheck($("#bookmarkName")))
									saveBookmark();
							}
						},{
							text: cancel_btn,
							click : function() {
								$("#bookmark_op").dialog("close");
							}
						}]
					});

					/* bookmark */
					$("#bookmarkButton").click(function() {
						var name = $("#dsname").text();
						$(".ftext").val(name);
						$("textarea").val("");
						$("#bookmark_op").parent().appendTo("#dialog_target");
						$("#bookmark_op").dialog("open");
						return false;
					});

					/* load */
					var dtitle;
					if(lang == 'en'){
						dtitle = "On Loading";
					}else if(lang == 'zh'){
						dtitle = "正在加载";
					}
					$("#onloading").dialog({
							bgiframe : true,
							autoOpen : false,
							draggable : false,
							closeOnEscape : false,
							closeText : false,
							resizable : false,
							width : 400,
							title : dtitle,
							modal : true,
					});
					
					$("#onloading").parent().appendTo("#dialog_target");
					$('a.ui-dialog-titlebar-close').hide();

					/* comment */
					var dtitle;
					if(lang == 'en'){
						dtitle = "Comment";
					}else if(lang == 'zh'){
						dtitle = "评论";
					}
					/*$("#comment_op").dialog({
							bgiframe : true,
							autoOpen : false,
							width : 400,
							title : dtitle,
							modal : true,
							buttons : [{
								text: ok_btn,
								click : function() {
									if (commentCheck($("#comment_textarea")))
										saveComment();
								}
							},{
								text: cancel_btn,
								click : function() {
									$("#comment_op").dialog("close");
								}
							}]
						});
					$("#addComment").click(function() {
						$(".ftext").val("");
						$("textarea").val("");
						$("#comment_op").parent().appendTo("#dialog_target");
						if($("#ugname") != null){
							$("#comment_op").dialog("open");
						}
						return false;
					});*/
					/*$("#editComment").click(function(){
						onClickEditComment();
					});*/
					$(".moreUris").click(function(){
						onClickMoreUris();
					});
					$(".lessUris").click(function(){
						onClickLessUris();
					});

					if ($("#user").val() == "null") {
						$(".button-bg").hide();
					}
					/*comment*/
					$("a.more-content").live("click",function(){
						var html = $(this).parent().find(".hidden").html();
						var parent = $(this).parent();
						parent.html(html);
						if(lang == 'en'){
							var less = $("<a class='less-content'>Less</a>");
						}else if(lang == 'zh'){
							var less = $("<a class='less-content'>收起</a>");
						}
						
						$(parent).append(less);
					});
					$("a.less-content").live("click",function(){
						var parent=$(this).parent();
						$(this).parent().find("a.less-content").remove();
						checkContentLengthInDs(parent);
					});
					
									
					// ======for new dataset
					$("#newDataset").click(function() {
						var ds_type = $(".entity-label").attr("ds_type");
						var genre = Genre;//(ds_type=="custom")?"c":"u";
						var datasetId = parseInt($(".entity-label").attr("datasetId"));
						if($("#ugname").length>0){
//							var location = "/sview/relations/dataset_create.jsp?genre="+ genre 
							var location = "/sview/relations/dataset_edit.jsp?genre="+ genre
							+ "&datasetId=" + datasetId
//							+ "&gid=" + gid
							+ "&idStr="+idStr
							+ "&lang=" + lang;
							window.location = location;
						}else{
							var url = window.location.href;
							var edit_authorDiv = createGroupSelectionDiv(getUser(), lang);
							$(edit_authorDiv).dialog({
								modal : true,
								minWidth : 450,
								height : 200,
								buttons : [{
									text: ok_btn,
									click :function() {
										var type = $(".edit_author").attr("t");
										if (type == "y") {
											var gid = $(".edit_author select>option:selected").attr("gid");
											var ds_type = $(".entity-label").attr("ds_type");
											var datasetId = parseInt($(".entity-label").attr("datasetId"));
											var genre = (ds_type=="custom")?"c":"u";
//											var location = "/sview/relations/dataset_create.jsp?genre="+ genre 
											var location = "/sview/relations/dataset_edit.jsp?genre="+ genre 
												+ "&datasetId=" + datasetId
//												+ "&gid=" + gid
												+ "&idStr="+idStr
												+ "&lang=" + lang;
//											alert(location);
											window.location = location;
										} else if (type == "n") {
											var paraString = encodeURIComponent(url);
											var location = "/sview/group/gmanage.jsp?from=" + paraString;
											if (lang == "zh")
												location = "/sview/group/gmanage.jsp?lang=zh&from=" + paraString;
											window.location = location;
										}
									}
								},{
										text: cancel_btn,
										click : function() {$(".edit_author").dialog("close");
									}
								}]
							});
						}
					});	//end of dsclick							
					// ========================
					/* input hints */
					$(".ftext").focus(function() {
						$(this).css("border-color", "#256EB1");
						$(this).parent().find(".error-msg").hide();
					});
					
					/*tabBar*/
					$(".tabBar").live("click",function(){
						onClickTabBar($(this));
					});
					$("#toCollection").live("click",function(){
						onClickToCollection($(this));
					});

					/* like dislike */
					var myCookieName = "ds_like_" + $("#dataset").val() + "_"
							+ $("#user").val();
					if ($.cookie(myCookieName) != null
							&& eval($.cookie(myCookieName)) == true) {
						$("#like").attr("disabled", "true");
						$("#dislike").attr("disabled", "true");
						$("#like").mouseover(function() {
							$(this).css("cursor", "default");
						});
						$("#dislike").mouseover(function() {
							$(this).css("cursor", "default");
						});
					} else {$("#like").click(function() {
						if ($.cookie(myCookieName) == null|| eval($.cookie(myCookieName)) == false) {
							$.cookie(myCookieName, 'true',{expires : 1,path : '/'});
							insertLike();
							$("#like").attr("disabled","true");
							$("#dislike").attr("disabled","true");
							$("#like").mouseover(function() {
								$(this).css("cursor","default");
								});
							$("#dislike").mouseover(function() {
								$(this).css("cursor","default");
								});
						}
					});					

						$("#dislike").click(function() {
							if ($.cookie(myCookieName) == null|| eval($.cookie(myCookieName)) == false) {
								$.cookie(myCookieName, 'true',
										{
											expires : 1,
											path : '/'
										});
								insertDisLike();
								$("#like").attr("disabled","true");
								$("#dislike").attr("disabled","true");
								$("#like").mouseover(function() {
											$(this).css("cursor","default");
										});
								$("#dislike").mouseover(function() {
											$(this).css("cursor","default");
										});
							}
						});
					}
					/* comment like dislike */
					var comments = new Array();
					var i = 0;
					$(".datasetComment").each(function() {
						comments.push($(this));
						i++;
					});

					for ( var x in comments) {
						var comment = comments[x];
						var cookieName = $(comment).attr("id") + $("#user").val();
						if ($.cookie(cookieName) != null
								&& eval($.cookie(cookieName)) == true) {
							$(comment).children("a").attr("disabled", "true");
							$(comment).children("a").mouseover(function() {
								$(this).css("cursor", "default");
							});
						} else {
							$(comment)
									.children("a")
									.first()
									.click(
											function() {
												var parent = $(this).parent(
														".datasetComment");
												var cookieName = parent
														.attr("id")
														+ $("#user").val();
												var commentID = parent
														.attr("commentID");
												if ($.cookie(cookieName) == null
														|| eval($
																.cookie(cookieName)) == false) {
													$.cookie(cookieName,
															'true', {
																expires : 1,
																path : '/'
															});
													insertCommentLike(
															commentID, $(this));
													parent.children("a").attr(
															"disabled", "true");
													parent
															.children("a")
															.mouseover(
																	function() {
																		$(this)
																				.css(
																						"cursor",
																						"default");
																	});
												}
											});

							$(comment)
									.children("a")
									.first()
									.next()
									.click(
											function() {
												var parent = $(this).parent(
														".datasetComment");
												var cookieName = parent
														.attr("id")
														+ $("#user").val();
												var commentID = parent
														.attr("commentID");
												if ($.cookie(cookieName) == null
														|| eval($
																.cookie(cookieName)) == false) {
													$.cookie(cookieName,
															'true', {
																expires : 1,
																path : '/'
															});
													insertCommentDisLike(
															commentID, $(this));
													parent.children("a").attr(
															"disabled", "true");
													parent
															.children("a")
															.mouseover(
																	function() {
																		$(this)
																				.css(
																						"cursor",
																						"default");
																	});
												}
											});
						}
					}
					var dtitle;
					if(lang == 'en'){
						dtitle = "Name conflict";
					}else if(lang == 'zh'){
						dtitle = "命名冲突";
					}
					$("#confirm")
							.dialog(
									{
										bgiframe : true,
										autoOpen : false,
										width : 400,
										title : dtitle,
										modal : true,
										buttons : [{
											text: continue_btn,
											click : function() {
												$(this).dialog("close");
												$("#bookmark_op").dialog("open");
											}},{
												text: cancel_btn,
												click : function() {
												$(this).dialog("close");
												$("#bookmark_op").dialog("close");
											}
										}]
									});
//					$("#tabs").tabs();
});//end of ready
/*comment edit
 * function onClickEditComment(){
	var input = $("<input id='comment_ipt' type='text'>");
	var comment = $("#comment").text();
	$(input).val(comment);
	var length = comment.length;
	$(input).attr("size",length+2);
	$("#comment").replaceWith(input);
	input.focus();
	
	var controler ;
	if(lang=="en"){
		controler = $("<span id='controler' class='commentOp'><a id='ec_ok' href='javascript:void(0)'>OK</a>&nbsp;&nbsp;<a id='ec_cancel' href='javascript:void(0)'>Cancel</a></span>");
	}else if(lang == "zh"){
		controler = $("<span id='controler' class='commentOp'><a id='ec_ok' href='javascript:void(0)'>完成</a>&nbsp;&nbsp;<a id='ec_cancel' href='javascript:void(0)'>取消</a></span>");
	}
	var editor = $("#editComment");
	$(editor).replaceWith(controler);
	
	$("#ec_cancel").click(function(){
		onClickCancelComment(comment);		
	});
	$("#ec_ok").live("click",onClickOKComment);
}
function onClickCancelComment(comment){
	var ncomment = $("<span id='comment'></span>");
	ncomment.text(comment);
	$("#comment_ipt").replaceWith(ncomment);
	
	var neditor;
	if(lang=="en"){
		neditor = $("<a id='editComment' class='commentOp' href='javascript:void(0);'>Edit</a>");
	}else if(lang == "zh"){
		neditor = $("<a id='editComment' class='commentOp' href='javascript:void(0);'>编辑</a>");
	}
	neditor.click(function(){onClickEditComment()});
	$("#controler").replaceWith(neditor);
}
function onClickOKComment(){
	if($("#ugname").length==0){
		if(lang == 'en'){
			alert("Please check your editing group!");
		}else if(lang == 'zh'){
			alert("请检查当前编辑组是否设置正确!");
		}
		return;
	}
	var data = {};
	data["comment"] = encodeURIComponent($("#comment_ipt").val());
//	data["userName"] = $("#user").val();
	data["groupName"] = $("#ugname").val();
	var ds = $("#dataset").val();
	data["ds_type"] = ds.substring(0, 1) == "c" ? "custom" : "uri";
	data["ds_id"] = ds.substring(1);
	data["lang"] = $("#display-lang").val();
	data = JSON.stringify(data);
	data = ("insert=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/commentInsert",
		dataType : "json",
		data : data,
		type : "post",
		success : function() {
			location.reload();
		}
	});
}*/
function onClickMoreUris(){
	if(Genre == TEMP_SHORT_GENRE){
		$(".statistics .docUri").show();
	}else{
		getFullSourceList();
	}

	if(lang=="en"){
		$("#urisOp").text("<<less");
	}else if(lang=="zh"){
		$("#urisOp").text("<<收起");
	}
	$("#urisOp").removeClass("moreUris");
	$("#urisOp").addClass("lessUris");
	$("#urisOp").unbind();
	$(".lessUris").click(function(){
		onClickLessUris();
	});
}
function getFullSourceList(){
	var data = {};
	data["ds_id"] = $("#ds_id").val();
//	data["ds_type"] = $("#ds_type").val();
	data["start"] = 0;
	data["length"] = $("#urisOp").attr("docNum");
	data["lang"] = lang;
	data = JSON.stringify(data);
	data = ("document=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/datasetDocs",
		dataType : "json",
		data : data,
		type : "post",
		success : function(result) {
			var lang = $("#display-lang").val();
			var array = result["result"];
			if(array.length>0){
				$(".docUri").remove();
				var brother = $("#source");
				for(var i=array.length-1; i>-1; i--){
					var element = array[i];
					var uri = $("<span class='docUri'></span>");
					$(uri).attr("id",element["id"]);
					$(uri).attr("order",i);
					uri.append("<br />&nbsp;&nbsp;&nbsp;&nbsp;");
					brother.after(uri);
					var a = $("<a></a>");
					var href = "/sview/dataset/u"+element["id"]+"?lang="+lang;
					$(a).attr("href",href);
					$(a).text(element["name"]);
					uri.append(a);
				}
			}
		}
	});
}
function onClickLessUris(){
	if(Genre == TEMP_SHORT_GENRE){
		$(".docUri").each(function(){
			if($(this).attr("order")>2){//========num-1 of init uris
				$(this).hide();
			}
		});
	}else{
		$(".docUri").each(function(){
			if($(this).attr("order")>2){//========num-1 of init uris
				$(this).remove();
			}
		});
	}
	
	if(lang=="en"){
		$("#urisOp").text("more>>");
	}else if(lang=="zh"){
		$("#urisOp").text("更多>>");
	}
	
	$("#urisOp").removeClass("lessUris");
	$("#urisOp").addClass("moreUris");
	$("#urisOp").unbind();
	$(".moreUris").click(function(){
		onClickMoreUris();
	});
}
function onClickTabBar(tabBar){
	$("#panel-entity-div").animate({height:450},"slow");
	$("#toCollectionDiv").animate({height:50},"slow");
	
	var a = $(tabBar).children("a");
	var op = $(a).attr("class");
	if(op == "expand"){
		var panel = "#"+$(tabBar).attr("id").replace("tab","panel");
		if($(panel).hasClass("showingPanel")){
			return;
		}else{
			//====for exclusively open
			var oldTab = $(".collapse").parent();
			onClickTabBar($(oldTab));
			//======
			$(panel).show();
			$(panel).addClass("showingPanel");
			$(a).removeClass("expand");
			$(a).addClass("collapse");
			$(a).attr("title","Collapse Panel");
			if(panel=="#panel-entity"){
				$("#toCollection").show();
			}
		}
	}else if(op == "collapse"){
		var panel = "#"+$(tabBar).attr("id").replace("tab","panel");
		$(panel).hide();
		$(panel).removeClass("showingPanel");
		$(a).removeClass("collapse");
		$(a).addClass("expand");
		$(a).attr("title","Expand Panel");
		if(panel=="#panel-entity"){
			$("#toCollection").hide();
		}
	}
}

function onClickToCollection(cbtn){
	if($(cbtn).linkbutton("options")["disabled"]){
		return;
	}
	var eids = "";
	$("#treeDiv #0 .jstree-checked").each(function(){
		var pidstr = $(this).attr("id")+"";
		if(pidstr.charAt(0) == "u"){
			eids += pidstr.substring(1, pidstr.length)+",";
		}
	});
	if(eids.length>0){
		eids = eids.substring(0, eids.length-1);
	}
	alert("selected entities:"+eids);
}

function insertCommentLike(commentID, el) {
	var data = {};
	data["id"] = commentID;
	data["like"] = "like";

	data = JSON.stringify(data);
	data = ("update=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/commentLikeDislike",
		dataType : "json",
		data : data,
		type : "post",
		success : function() {
			el.children("span").text(eval(el.children("span").text()) + 1);
		}
	});
}

function insertCommentDisLike(commentID, el) {
	var data = {};
	data["id"] = commentID;
	data["like"] = "dislike";

	data = JSON.stringify(data);
	data = ("update=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/commentLikeDislike",
		dataType : "json",
		data : data,
		type : "post",
		success : function() {
			el.children("span").text(eval(el.children("span").text()) + 1);
		}
	});
}

function saveBookmark() {
	var data = {};
	data["bookmarkName"] = encodeURIComponent($("#bookmarkName").val());
	data["userName"] = $("#user").val();
	data = JSON.stringify(data);
	data = ("exist=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/bookmarkIsExist",
		dataType : "json",
		data : data,
		type : "post",
		success : function(result) {
			if (eval(result["exist"]) == true) {
				$(".dname").html($("#bookmarkName").val());
				$(".dsname_dis").html($("#dsname").attr("title"));
//				$(this).dialog("close");
				$("#confirm").dialog("open");
			} else if (eval(result["exist"]) == false) {
				// do
				var data = {};
				data["bookmarkName"] = encodeURIComponent($("#bookmarkName")
						.val());
				data["userName"] = $("#user").val();
				var ds = $("#dataset").val();
				data["ds_type"] = ds.substring(0, 1) == "c" ? "custom" : "uri";
				data["ds_id"] = ds.substring(1);
				data["lang"] = $("#display-lang").val();
				data = JSON.stringify(data);
				data = ("insert=" + encodeURIComponent(data));
				$.ajax({
					url : "/sview/bookmarkInsert",
					dataType : "json",
					data : data,
					type : "post",
					success : function() {
						$("#bookmark_op").dialog("close");
					}
				});
			}
		}
	});
}

/*function saveComment() {
	var data = {};
	data["comment"] = encodeURIComponent($("#comment_textarea").val());
//	data["userName"] = $("#user").val();
	var ds = $("#dataset").val();
	data["ds_type"] = ds.substring(0, 1) == "c" ? "custom" : "uri";
	data["ds_id"] = ds.substring(1);
	data["lang"] = $("#display-lang").val();
	data = JSON.stringify(data);
	data = ("insert=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/commentInsert",
		dataType : "json",
		data : data,
		type : "post",
		success : function() {
			$("#comment_op").dialog("close");
			location.reload();
		}
	});
}*/
function blurState(e) {
	$(e).css("border-color", "#BDC7D8");
}

function insertLike() {
	var name = $("#like").attr("name");
	var data = {};
	data["ds_type"] = name.substring(0, 1) == "c" ? "custom" : "uri";
	data["ds_id"] = name.substring(1);
	data["like"] = 1;
	data["dislike"] = 0;

	data = JSON.stringify(data);
	data = ("insert=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/likeDislike",
		dataType : "json",
		data : data,
		type : "post",
		success : function() {
			$("#like").children("span").text(
					eval($("#like").children("span").text()) + 1);
		}
	});
}

function onLoading() {
	$("#onloading").dialog("open");
}

function closeLoading() {
	$("#onloading").dialog("close");
}

function insertDisLike() {
	var name = $("#dislike").attr("name");
	var data = {};
	data["ds_type"] = name.substring(0, 1) == "c" ? "custom" : "uri";
	data["ds_id"] = name.substring(1);
	data["like"] = 0;
	data["dislike"] = 1;

	data = JSON.stringify(data);
	data = ("insert=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/likeDislike",
		dataType : "json",
		data : data,
		type : "post",
		success : function() {
			$("#dislike").children("span").text(
					eval($("#dislike").children("span").text()) + 1);
		}
	});
}

function nameCheck(e) {
	var displayLang = $("#display-lang").val();
	var flag = true;
	blurState(e);
	var val = $(e).val();
	if (val == "") {
		var msg = $(e).parent().find(".error-msg");
		var textEn = "Please enter a name";
		var textZhSimple = "请输入名字";
		if (displayLang == "en")
			msg.text(textEn);
		else if (displayLang == "zh")
			msg.text(textZhSimple);
		msg.show();
		$(e).css("border-color", "red");
		flag = false;
	}
	if (!flag)
		return false;
	return true;
}

function commentCheck(e) {
	var displayLang = $("#display-lang").val();
	var flag = true;
	blurState(e);
	var val = $(e).val();
	if (val == "") {
		var msg = $(e).parent().find(".error-msg");
		var textEn = "Please enter a comment";
		var textZhSimple = "请输入评论";
		if (displayLang == "en")
			msg.text(textEn);
		else if (displayLang == "zh")
			msg.text(textZhSimple);
		msg.show();
		$(e).css("border-color", "red");
		flag = false;
	}
	if (!flag)
		return false;
	return true;
}

function checkContentLengthInDs(e) {
	var displayLang = $("#display-lang").val();
	var str = $(e).html();
	if (str != null && str.length > 500) {
		var content = str.substring(0, 500) + "...";
		$(e).html(content);
		var more;
		if(displayLang == 'en'){
			more = $("<a class='more-content'>More</a>");
		}else{
			more = $("<a class='more-content'>更多</a>");
		}
		$(e).append(more);
		var hidden = $("<div class='hidden'></div>").html(str);
		$(e).append(hidden);
	}
}
